package demo.android.myapplication.demos.views

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import android.util.AttributeSet
import android.view.View
import androidx.annotation.IntRange
import androidx.annotation.RequiresApi
import cn.android.basic.centerX
import cn.android.basic.centerY
import cn.android.basic.dp
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.tan

/**
 * <br>createBy Gw
 * <br>createTime: 2021/7/7 09:10
 */
class PieView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    val angles = arrayOf(30f, 60f, 90f, 120f, 10f, 50f)
    val colos = arrayOf(Color.RED, Color.GRAY, Color.BLUE, Color.YELLOW, Color.GREEN, Color.MAGENTA)
    private val radius = 90.dp
    val gap = 10.dp

    @IntRange(from = 0, to = 5)
    private var selected = 1

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        var startAngle = 0f
        for ((index, angle) in angles.withIndex()) {
            paint.color = colos[index]

            var cacheAngle = startAngle
            if(selected == index) {
                canvas.save()
                canvas.rotate(startAngle, centerX, centerY)
                canvas.translate(gap, (tan(Math.toRadians(angle.toDouble() / 2)) * gap).toFloat())
                startAngle = 0f
            }

            canvas.drawArc(centerX - radius, centerY - radius, centerX + radius, centerY + radius,
                startAngle, angle, true, paint)

            if(selected == index) {
                canvas.restore()
                startAngle = cacheAngle
            }

            startAngle += angle
        }
    }
}